package org.nimi317.web_gis.utils;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.nimi317.web_gis.exception.E;
import org.nimi317.web_gis.exception.RException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author thunderobot
 */
@Component
@ConditionalOnProperty(value = "spring.mail.username")
@Slf4j
public class EmailUtils {

    @Value("${spring.mail.username}")
    private String email;

    @Autowired
    private JavaMailSender javaMailSender;

    @Async
    public void sendEmail(String toEmail, String subject, String content) throws MessagingException {
        MimeMessage mi = javaMailSender.createMimeMessage();
        MimeMessageHelper mailMessage = new MimeMessageHelper(mi);
        mailMessage.setFrom(email);
        mailMessage.setTo(toEmail);
        mailMessage.setText(content, true);
        Date date = new Date();
        mailMessage.setSentDate(date);
        mailMessage.setSubject(subject);
        javaMailSender.send(mailMessage.getMimeMessage());
        log.info("在{}正在发送右键到{}内容为:{}", date, toEmail, content);
    }

    public void checkEmail(String email) throws RException {
        //检验email是否符合规范
        if (!email.matches("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$")) {
            log.info("{}的邮箱不符合规范", email);
            throw new RException(E.EmailNotAllowException);
        }
    }
}
